//
//  VOLLoginViewController.m
//  Volver
//
//  Created by administrator on 14-9-20.
//  Copyright (c) 2014年 vol. All rights reserved.
//

#import "VOLLoginViewController.h"

#import "common.h"
#import "HTTPDefine.h"

#import "ASIFormDataRequest.h"
#import "MBProgressHUD.h"

#import "VOLAppDelegate.h"
#import "VOLRegisterViewController.h"

@interface VOLLoginViewController ()
{
    VOLAppDelegate *del;
    
}

@end

@implementation VOLLoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    NSLog(@"loginViewdidload");
    
    //获取整个程序的全局变量
    del = kGetDel;
    
    //设置输入框的代理
    self.phoneLabel.delegate = self;
    self.passwordLabel.delegate = self;
    
    [self loadUserInfo];
    
    
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark 显示时加载内容
-(void)viewWillAppear:(BOOL)animated{
    [self loadUserInfo];
}


#pragma mark 加载已存储在本地的用户
-(void)loadUserInfo{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    self.phoneLabel.text = [userDefaults stringForKey:@"userPhone"];
    self.passwordLabel.text = [userDefaults stringForKey:@"userPassword"];
}
#pragma mark 点击空白处收回键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.4 animations:^{
        self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }];
}

#pragma mark 跳转注册界面
- (IBAction)goToRegister:(id)sender {
    
    VOLRegisterViewController *registervc = [self.storyboard instantiateViewControllerWithIdentifier:@"registerController"];
    registervc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentViewController:registervc animated:YES completion:^{
        
    }];
}


#pragma mark 用户登录
- (IBAction)userLogin:(id)sender {
    NSLog(@"登录");
    NSString *alertMessage;
    NSString *userPhone = self.phoneLabel.text;
    NSString *userPassword = self.passwordLabel.text;
    
    //判断输入内容是否为空
    if ([userPhone isEqualToString:@""]) {
        alertMessage = @"手机号不能为空！";
        if ([userPassword isEqualToString:@""]) {
            alertMessage = @"手机号和密码不能为空！";
        }
    }else if ([userPassword isEqualToString:@""]){
        alertMessage = @"密码不能为空！";
    }
    else if (![self isValidPhoneNumber:userPhone]){//判断是否为有效手机号
        alertMessage = @"请输入正确的手机号！";
    }
    
    if (alertMessage != nil) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:alertMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    NSLog(@"联网登录");
    
    __block MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    //登录结果
    __block int result;
    [HUD showAnimated:YES whileExecutingBlock:^{
        //调用登录方法登录
        result = [del userLoginUserPhone:userPhone userPassword:userPassword];
    } completionBlock:^{
        
        //清除HUD
        [HUD removeFromSuperview];
        HUD = nil;
        
        switch (result) {
            case -1://账号不存在
            {
                HUD = [[MBProgressHUD alloc] initWithView:self.view];
                [self.view addSubview:HUD];
                HUD.mode = MBProgressHUDModeText;
                HUD.labelText = @"账号不存在，请先注册账号";
                [HUD showAnimated:YES whileExecutingBlock:^{
                    sleep(1);
                } completionBlock:^{
                    //用户名和密码置空
                    self.phoneLabel.text = @"";
                    self.passwordLabel.text = @"";
                    
                    //自动登录置0，保存
                    del.isAutologin = 0;
                    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                    [userDefaults setValue:[NSString stringWithFormat:@"%d",del.isAutologin] forKey:@"isAutoLogin"];
                    
                    //保存内容
                    [userDefaults setValue:@"" forKey:@"userPhone"];
                    [userDefaults setValue:@"" forKey:@"userPassword"];
                    
                    //清除HUD
                    [HUD removeFromSuperview];
                    HUD = nil;
                }];
            }
                break;
            case 0://密码错误
            {
                HUD = [[MBProgressHUD alloc] initWithView:self.view];
                [self.view addSubview:HUD];
                HUD.mode = MBProgressHUDModeText;
                HUD.labelText = @"密码错误，请重新输入";
                [HUD showAnimated:YES whileExecutingBlock:^{
                    sleep(1);
                } completionBlock:^{
                    //置空密码
                    self.passwordLabel.text = @"";
                    
                    //自动登录置0，保存
                    del.isAutologin = 0;
                    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                    [userDefaults setValue:[NSString stringWithFormat:@"%d",del.isAutologin] forKey:@"isAutoLogin"];
                    
                    //保存内容
                    [userDefaults setValue:self.phoneLabel.text forKey:@"userPhone"];
                    [userDefaults setValue:self.passwordLabel.text forKey:@"userPassword"];
                    
                    
                    //清除HUD
                    [HUD removeFromSuperview];
                    HUD = nil;
                }];
            }
                break;
            case 1://登录成功
            {
                //将自动登录设置为YES，并使用NSUserDefaults写进文件，当注销时将它再改成NO
                del.isAutologin = 1;
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setValue:[NSString stringWithFormat:@"%d",del.isAutologin] forKey:@"isAutoLogin"];
                
                //保存当前登录的用户
                [userDefaults setValue:userPhone forKey:@"userPhone"];
                [userDefaults setValue:userPassword forKey:@"userPassword"];
                
                
                
                [self dismissViewControllerAnimated:YES completion:^{
                    
                }];
            }
                break;
                
        }
        
        
    }];
    
}

#pragma mark - 验证手机号码是否是有效的
-(BOOL)isValidPhoneNumber:(NSString *)phone{
    
    NSString *phoneRegex = @"^1[3|5|7|8|][0-9]{9}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:phone];
    
}

#pragma mark 关闭登录界面
- (IBAction)closeView:(id)sender {
    [self dismissViewControllerAnimated:YES completion:^{
        //后续操作
    }];
}

#pragma mark - Text Field 代理方法

#pragma mark 解决键盘遮挡
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    CGRect frame = textField.frame;
    //判断键盘弹出时是否会遮挡输入框，输入框高度30，键盘高度216
    int offset = frame.origin.y + frame.size.height + 15 - (self.view.frame.size.height - 216);
    [UIView animateWithDuration:0.4 animations:^{
        if (offset > 0) {
            CGRect viewFrame = self.view.frame;
            self.view.frame = CGRectMake(0, -offset, viewFrame.size.width, viewFrame.size.height);
        }
    }];
    return YES;
}
#pragma mark 还原输入框位置
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.4 animations:^{
        self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }];
    return YES;
}


@end
